<template>
  <div class="visualDesign-table">
    <pagination :pagination="formData" @currpage="getData" float="right" :total="total"></pagination>
    <el-table
      ref="table"
      :data="tableData"
      :header-cell-style="getRowClass"
      v-loading="loading"
      @sort-change="sortthiscolumn"
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="expand" fixed="left">
        <template slot-scope="scope">
          <div
            class="expan"
            v-if="scope.row.visionDemandUserRelList.length > 0 && scope.row.visionDemandCheckRelList.length > 0"
          >
            <div class="expandTitle">负责人</div>
            <el-table :data="scope.row.visionDemandUserRelList">
              <el-table-column prop="startTime" label="开始结束时间" width="250">
                <template slot-scope="demand">
                  {{demand.row.startTime | formatDate}}-{{demand.row.endTime | formatDate}}
                  <el-button
                    type="danger"
                    @click="$refs.datePicker.show(demand.row.userId,scope.row.visionDemandId)"
                    :disabled="!(demand.row.userId ===  $store.getters.userId && scope.row.visionDemandStatusId  === 5)"
                    size="mini"
                  >修改</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="updateTime" label="修改时间" width="200">
                <template slot-scope="demand">{{demand.row.updateTime | formatDateHMS}}</template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="150">
                <template slot-scope="demand">{{demand.row.status | getStatus}}</template>
              </el-table-column>
              <el-table-column prop="userName" label="设计师" width="120"></el-table-column>
              <el-table-column prop="isHelper" label="是否需要协助">
                <template
                  slot-scope="demand"
                >{{demand.row.isHelper == '0' ?'独立完成：':'需要协助：'}} {{demand.row.helperContent}}</template>
              </el-table-column>
              <el-table-column>
                <template slot-scope="demand">
                  <el-button
                    v-if="demand.row.userId === $store.getters.userId && scope.row.visionDemandStatusId >= 5 && scope.row.visionDemandStatusId < 9"
                    type="primary"
                    size="mini"
                    @click="principalStatus(scope.row,scope.row.visionDemandStatusId)"
                  >录入会议记录</el-button>
                  <el-alert
                    v-if="demand.row.userId === $store.getters.userId && (scope.row.visionDemandStatusId === 4 && demand.row.status === 1)"
                    title="等待其他设计师领取任务"
                    type="warning"
                  ></el-alert>
                  <el-button
                    v-else-if="demand.row.userId === $store.getters.userId && [4,6,7].indexOf(scope.row.visionDemandStatusId) != -1&& demand.row.status !== 3 "
                    :type="demand.row.status === 0 ? 'primary' : demand.row.status === 1?'success':'warning' "
                    size="mini"
                    @click="principalStatus(scope.row,demand.row.status)"
                  >
                    <template v-if="demand.row.status === 0 ">领任务</template>
                    <template v-else-if="demand.row.status === 1 ">开始任务</template>
                    <template v-else-if="demand.row.status === 2 ">完成</template>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="expandTitle">审核人</div>
            <el-table :data="scope.row.visionDemandCheckRelList">
              <el-table-column prop="getReviewerStatus" label="状态" width="140">
                <template slot-scope="demand">{{demand.row.checkStatus | getReviewerStatus}}</template>
              </el-table-column>
              <el-table-column prop="userDisplayName" label="审核人" width="120"></el-table-column>
              <el-table-column prop="updateTime" label="修改时间" width="150">
                <template slot-scope="demand">{{demand.row.updateTime | formatDateHMS}}</template>
              </el-table-column>
              <el-table-column label="操作" width="220">
                <template slot-scope="demand">
                  <template
                    v-if="demand.row.userId === $store.getters.userId && scope.row.visionDemandStatusId === 8  && demand.row.checkStatus === 0 "
                  >
                    <el-button
                      type="primary"
                      size="mini"
                      @click="$refs.Review.show(scope.row,demand.row,1)"
                    >通过</el-button>
                    <el-button
                      type="danger"
                      size="mini"
                      @click="$refs.Review.show(scope.row,demand.row,-1)"
                    >拒绝</el-button>
                  </template>
                  <el-alert
                    v-else-if="demand.row.userId === $store.getters.userId && scope.row.visionDemandStatusId === 8  && demand.row.checkStatus === 1"
                    title="等待其他审核人通过"
                    type="warning"
                  ></el-alert>
                </template>
              </el-table-column>
              <el-table-column prop="denialCount" label="拒绝次数" width="80"></el-table-column>
              <el-table-column prop="denialReason" label="拒绝原因">
                <template slot-scope="scope">
                  <el-timeline>
                    <el-timeline-item
                      v-for="(activity, index) in JSON.parse(scope.row.denialReason )"
                      :key="index"
                      :timestamp="activity.timestamp"
                    >{{activity.content}}</el-timeline-item>
                  </el-timeline>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="visionDemandName" label="需求" width="250">
        <template slot-scope="scope">
          <router-link
            :to="{name:'visualDesignDetails', query: scope.row}"
            class="visionDemandName"
          >{{scope.row.visionDemandName}}</router-link>
        </template>
      </el-table-column>
      <el-table-column prop="businessUnit" label="BU" width="100"></el-table-column>
      <el-table-column prop="productCategory" label="产品系列" width="100"></el-table-column>
      <el-table-column prop="productModelNumber" label="型号" width="100">
        <template slot-scope="scope">
        <el-link :href="'#/dashboard?productId=' + scope.row.productId+'&productModelNumber=' + scope.row.productModelNumber
        + '&productCategoryId=' + scope.row.productCategoryId +'&productCategory='+ scope.row.productCategory
        +'&businessUnitId=' +  scope.row.businessUnitId  +'&businessUnit='+  scope.row.businessUnit ">{{ scope.row.productModelNumber}}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="visionDemandType" label="需求类型" width="150">
        <template slot-scope="scope">
          <span
            v-if="scope.row.visionDemandType && VisionDemandTypeList.length > 0"
          >{{VisionDemandTypeList.find(item => item.key === scope.row.visionDemandType).value}}</span>
          <div v-if="scope.row.visionDemandType === 2">日均浏览量：{{scope.row.pageViewsPercentage}}</div>
          <div
            v-if="scope.row.visionDemandType === 2"
          >日均转化率：{{(scope.row.unitSessionPercentage * 100).toFixed(2)}}%</div>
        </template>
      </el-table-column>

      <el-table-column prop="createUserName" label="创建人" width="140">
      </el-table-column>
      <el-table-column prop="deliveryTime" sortable="custom" label="发货时间 " width="120">
        <template slot-scope="scope">
          {{scope.row.deliveryTime | formatDate}}
          <i
            class="el-icon-edit"
            @click="$refs.upDate.show(scope.row)"
            v-if="scope.row.createUserId ===  $store.getters.userId"
          ></i>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" sortable="custom" label="提出时间" width="150">
        <template slot-scope="scope">{{scope.row.createTime | formatDateHMS}}</template>
      </el-table-column>
      <el-table-column prop="predictResultImgTotal" label="预测张数" width="80"></el-table-column>
      <el-table-column prop="actualResultImgTotal" label="实际张数" width="80"></el-table-column>
      <el-table-column prop="updateUserName" label="修改人" width="100"></el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="150">
        <template slot-scope="scope">{{scope.row.updateTime | formatDateHMS}}</template>
      </el-table-column>
      <el-table-column prop="statusName" label="状态" width="160">
        <template slot-scope="scope">
          <el-button
            v-if="RoleTypeByUserId.indexOf(scope.row.visionDemandStatusId) != -1 && [1,2,3].indexOf(scope.row.visionDemandStatusId) != -1"
            type="primary"
            @click="reviewStatus(scope.row)"
            size="mini"
          >{{scope.row.statusName}}</el-button>
          <el-tag v-else>{{scope.row.statusName}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="demandUser" label="指派负责人" min-width="90"></el-table-column>
      <el-table-column prop="endTime" label="任务开始完成时间" width="180">
        <template slot-scope="scope">
          <span
            :style="scope.row | formatDateColor"
          >{{scope.row.startTime |formatDate }} - {{scope.row.endTime | formatDate}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="endTime"
        label="操作"
        fixed="right"
        :width="(updatePrincipal ?350:250) +  (copyDemand?70:0)"
      >
        <template slot-scope="scope">
          <el-button
            type="success"
            @click="$refs.taskPerson.show(scope.row,isBrandDirectorByUserId)"
            size="mini"
            v-if="updatePrincipal"
            :disabled="scope.row.visionDemandStatusId >= 8  || scope.row.visionDemandStatusId < 4"
          >修改负责人</el-button>
          <el-button
            type="warning"
            @click="$router.push({ path: '/OACenter/visualDesign/vision' ,query:scope.row})"
            :disabled="scope.row.createUserId !==  $store.getters.userId || scope.row.visionDemandStatusId  === 9"
            size="mini"
          >编辑</el-button>
          <el-button
            type="danger"
            @click="deleteVision( scope.row.visionDemandId )"
            :disabled="  $store.getters.roles.indexOf(1) == -1 ? (scope.row.createUserId !==  $store.getters.userId ||  scope.row.visionDemandStatusId  > 2) : false  "
            size="mini"
          >删除 </el-button>
          <el-button
            type="primary"
            @click="$router.push({ path: '/OACenter/visualDesign/revealImages' ,query:scope.row})"
            size="mini"
            :disabled="scope.row.visionDemandStatusId  < 4"
          >视觉展示</el-button>
          <el-button
            type="primary"
            @click="copyVisionDesign(scope.row)"
            v-if="copyDemand"
            size="mini"
          >拷贝 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <scroll-table ref="scrollTable"></scroll-table>
    <table-taskPerson ref="taskPerson" @loadData="getData" ></table-taskPerson>
    <table-task ref="task" @loadData="getData"></table-task>
    <table-meetingMinutes ref="meetingMinutes" @loadData="getData"></table-meetingMinutes>
    <table-Review ref="Review" @loadData="getData"></table-Review>
    <up-date-picker ref="datePicker" @loadData="getData"></up-date-picker>
    <up-date ref="upDate" @loadData="getData"></up-date>



    <div>
      <el-dialog title="拷贝视觉需求" :visible.sync="dialogFormVisible" width="500px" >

          <el-form  :model="designData" >

            <el-form-item prop="checkerList" label="创建人" label-width="60px">
              <el-select
                placeholder="请选择创建人"
                size="small"
                filterable
                v-model="designData.createUserId"
              >
                <el-option
                  v-for="item in DepartmentUser"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.userName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button
              type="primary"
              @click="copyVisionDesignById()"
              size="small"
            >拷贝</el-button>
          </div>

      </el-dialog>
    </div>

  </div>
</template>
<script>
// 0待领取任务 1:已领取任务 2:开始任务 3:完成任务

// '1', '运营主管审核'
// '2', '品牌部主管审核'
// '3', '待指派'
// '4', '待领任务'  // 0待领取任务
// '5', '录入会议记录'
// '6', '开始任务'  //1:已领取任务
// '7', '进行中'  //2:开始任务
// '8', '审核中' //完成任务
// '9', '已完成'
const ERR_OK = 200;
import tableTaskPerson from "./table-taskPerson";
import upDatePicker from "./table-Update-picker.vue";
import upDate from "./table-Update.vue";
import tableTask from "./table-task";
import tableMeetingMinutes from "./table-meetingMinutes";
import tableReview from "./table-Review";
import { formatDate } from "assets/js/date";
import pagination from "components/pagination";
import scrollTable from "components/scroll/scroll-table.vue";
import { checkPermission } from "@/utils/permissions";
export default {
  data() {
    return {
      dialogFormVisible: false,
      tableData: [],
      loading: true,

      formData: {},
      RoleTypeByUserId: [],
      total: 1,
      VisionDemandTypeList: [],
      isBrandDirectorByUserId: false,
      copyDemand: checkPermission('visionDemand:DemandList:CopyDemand'),
      principal: checkPermission('visionDemand:DemandList:principal'),
      updatePrincipal: checkPermission('visionDemand:DemandList:updatePrincipal'),
      updateCreateUser: checkPermission('visionDemand:DemandList:updateCreateUser'),
      DepartmentUser: [],
      designData:{
        createUserId: "",
        visionDemandId: ""

    }



      };
  },
  filters: {
    formatDateColor({ visionDemandCheckRelList, endTime }) {
      if (visionDemandCheckRelList && visionDemandCheckRelList.find(item => item.updateTime)) {
        var flag = true;
        for (let i in visionDemandCheckRelList) {
          let item = visionDemandCheckRelList[i];
          if(!item.updateTime) continue;
          if ( new Date(formatDate(new Date(item.updateTime), "yyyy-MM-dd")).valueOf() <= new Date(formatDate(new Date(endTime), "yyyy-MM-dd")).valueOf() ) {
            flag = false;
            return "";
          }
        }
        if(flag){
          return "color: rgb(255, 17, 0);";
        }
      }
    },
    formatDate(time) {
      if (time) {
        var date = new Date(time);
        return formatDate(date, "yyyy-MM-dd");
      }
    },
    formatDateHMS(time) {
      if (time) {
        var date = new Date(time);
        return formatDate(date, "yyyy-MM-dd hh:mm:ss");
      }
    },
    getStatus(key) {
      switch (key) {
        case 0:
          return "待领取";
          break;
        case 1:
          return "已领取";
          break;
        case 2:
          return "进行中";
          break;
        case 3:
          return "已完成";
          break;
        default:
          return "待领取";
          break;
      }
    },
    getReviewerStatus(key) {
      switch (key) {
        case -1:
          return "未通过审核";
          break;
        case 0:
          return "待审核";
          break;
        case 1:
          return "通过审核";
          break;
      }
    }
  },
  created() {
    this.getRoleTypeByUserId();
    this.getVisionDemandTypeList();
    this.getSaleSupervisorByUserId();
    this.getDepartmentUser()
  },
  methods: {
    getDepartmentUser() {
      this.$ajax({
        method: "get",
        url: "/system/user/getDeptUserList"
      }).then(res => {
        if (res.data.code === ERR_OK) {
          this.DepartmentUser = res.data.rows;
        }
      });
    },
      getData(formData) {
      if (formData) {
        this.formData = formData;
      }
      this.loading = true;
      this.$ajax({
        method: "post",
        url: this.GLOBAL.oaVisionDemand + "/visionDemand/getVisionDemandList",
        data: this.formData
      }).then(res => {
        this.loading = false;
        if (res.data.code === ERR_OK) {
          this.tableData = res.data.data.data;
          this.total = res.data.data.total;
          this.$nextTick(() => {
            this.$refs.scrollTable.scrollShow(this.$refs.table);
          });
        }
      });
    },
    tableRowClassName({ row, rowIndex }) {
      let ban = "";
      if (
        row.visionDemandUserRelList.length === 0 &&
        row.visionDemandCheckRelList.length === 0
      ) {
        ban = "banIcon";
      }
      if (rowIndex % 2) {
        return "warning-row " + ban;
      } else {
        return "success-row " + ban;
      }
    },
    //主管审核
    reviewStatus(item) {
      switch (item.visionDemandStatusId) {
        case 1:
          this.supervisorCheck(item);
          break;
        case 2:
          this.supervisorCheck(item);
          break;
        case 3:
          this.$refs.taskPerson.show(item);
          break;
        default:
          break;
      }
    },
    //负责人
    principalStatus(item, status) {

      switch (status) {
        case 0:
          this.$refs.task.show(item);
          break;
        case 5:
          this.$refs.meetingMinutes.show(item);
          break;
        case 6:
          this.$refs.meetingMinutes.show(item);
          break;
        case 7:
          this.$refs.meetingMinutes.show(item);
          break;
        case 8:
          this.$refs.meetingMinutes.show(item);
          break;
        case 1:
          this.updDesignerChangeTaskStatus(item, "是否开始任务");
          break;
        case 2:
          this.updDesignerChangeTaskStatus(item, "是否完成任务");
          break;
        default:
          break;
      }
    },
    //审核人通过
    updDesignerChangeTaskStatus(item, txt) {
      this.$confirm(txt, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$ajax({
            method: "post",
            url:
              this.GLOBAL.oaVisionDemand +
              "/visionDemandStatus/designerChangeTaskStatus",
            data: {
              updateUserId: this.$store.getters.userId,
              visionDemandId: item.visionDemandId,
              visionDemandStatusId: item.visionDemandStatusId
            }
          }).then(res => {
            if (res.data.code === ERR_OK) {
              this.getData();
              this.$message.success(res.data.msg);
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },
    //主管审核(运营主管,品牌部主管)
    supervisorCheck(item) {
      this.$confirm("是否审核通过", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$ajax({
            method: "post",
            url:
              this.GLOBAL.oaVisionDemand +
              "/visionDemandStatus/supervisorCheck",
            data: {
              updateUserId: this.$store.getters.userId,
              visionDemandId: item.visionDemandId,
              visionDemandStatusId: item.visionDemandStatusId
            }
          }).then(res => {
            if (res.data.code === ERR_OK) {
              this.getData();
              this.$message.success("审核成功");
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },
    //获取审核权限
    getRoleTypeByUserId() {
      this.$ajax
        .get(
          this.GLOBAL.oaVisionDemand +
            "/userHandler/findRoleTypeByUserId?userId=" +
            this.$store.getters.userId
        )
        .then(res => {
          if (res.data.code === ERR_OK && res.data.data) {
            this.RoleTypeByUserId = res.data.data;
          }
        });
    },
    //获取是否运营主管
    getSaleSupervisorByUserId() {
      this.$ajax
        .get(
          this.GLOBAL.oaVisionDemand +
            "/userHandler/isBrandDirectorByUserId?userId=" +
            this.$store.getters.userId
        )
        .then(res => {
          if (res.data.code === ERR_OK) {
            this.isBrandDirectorByUserId = res.data.data;
          }
        });
    },

    //获取视觉需求类型列表
    getVisionDemandTypeList() {
      this.$ajax
        .get(
          this.GLOBAL.oaVisionDemand +
            "/visionDemandBasicInfo/getVisionDemandTypeList"
        )
        .then(res => {
          if (res.data.code === ERR_OK) {
            this.VisionDemandTypeList = res.data.data;
          }
        });
    },
    //排序
    sortthiscolumn({ column, prop, order }) {
      let Sort = "";
      let formData = {
        sortField: prop === "createTime" ? "create_time" : "delivery_time",
        sortMode:
          order === "ascending" ? "asc" : order === "descending" ? "desc" : ""
      };
      this.formData = { ...this.formData, ...formData };
      this.getData(this.formData);
    },
    //删除
    deleteVision(id) {
      this.$confirm("是否确定删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$ajax
            .delete(
              this.GLOBAL.oaVisionDemand +
                "/visionDemand/deleteVisionDemandById?visionDemandId=" +
                id
            )
            .then(res => {
              if (res.data.code === ERR_OK) {
                this.$message.success("删除成功");
                this.getData(this.formData);
              } else {
                this.$message.error(res.data.msg);
              }
            });
        })
        .catch(() => {});
    },
    // 标题背景颜色
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background: #EBEEF5 ";
      } else {
        return "";
      }
    },
    //拷贝弹窗
    copyVisionDesign(row){
      this.dialogFormVisible = true
      this.designData.visionDemandId = row.visionDemandId

    },
    //确认拷贝
    copyVisionDesignById(){
      this.$confirm("确定拷贝需求？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$ajax
            .get(
              this.GLOBAL.oaVisionDemand +
              "/visionDemand/copyVisionDesignById?visionDemandId=" + this.designData.visionDemandId + "&createUserId=" + this.designData.createUserId
            )
            .then(res => {
              if (res.data.code === ERR_OK) {
                this.$message.success(res.data.msg);
                this.getData(this.formData);
              } else {
                this.$message.error(res.data.msg);
              }
              //关闭弹窗  重置数据
              this.dialogFormVisible = false
              this.designData = {
                createUserId: "",
                visionDemandId: ""
              }
            });
        })
        .catch(() => {});
    },

  },
  components: {
    tableTaskPerson,
    tableTask,
    tableMeetingMinutes,
    tableReview,
    pagination,
    scrollTable,
    upDatePicker,
    upDate
  }
};
</script>
<style lang="stylus" scoped>
.visionDemandName {
  color: #409EFF;
  text-decoration: underline;
}

.expan {
  padding: 0 50px 15px 50px;
}

.expandTitle {
  margin-left: 5px;
  margin-top: 15px;
  font-size: 14px;
  font-weight: bold;
  color: #000;
}

.el-icon-edit {
  cursor: pointer;
}

.el-tag {
  color: #000000;
  font-weight: bold;
  border-color: #409eff;
  background-color: transparent;
  width: 100%;
  text-align: center;
}
</style>
<style lang="stylus">
.visualDesign-table {
  .el-table .warning-row {
    background: #ebeef5;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .el-table__expand-icon {
    height: 20px;
    width: 20px;
    border: 1px solid #409eff;
    color: #fff;
    background: #409eff;
  }

  .el-icon {
    font-weight: bold;
  }

  .banIcon {
    .el-table__expand-icon {
      color: #c0c4cc;
      cursor: not-allowed;
      background: transparent;
      color: #000000;
      transform: rotate(0);
    }
  }
}
</style>
